// service/login/login.js
const app = getApp()
import http from "../../utils/http"
import util from "../../utils/util"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    agree: false,
    code: '',
    avatarUrl: '',
    nickname: '',
    show: false,
    safeBottom: `30px`,
    refuse: false,
    waitSHow: false,
    note: '',
    token: '',
    config: '',
    userInfo: '',
    mobile: "",
    captcha: "",
    countdown: 0,
    getCodeCountdownInter: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const high = app.globalData.safeBottom
    this.setData({
      safeBottom: `${high}px`
    })
    this.getCode();
  },
  onLoadConfig(option) {
    this.setData({
      config: app.globalData.config
    })
  },
  infoTap(e) {
    let info = e.currentTarget.dataset.info
    let name = e.currentTarget.dataset.name
    let id = app.globalData.config[info]
    util.skip('/service/info/info?id=' + id + '&name=' + name)
  },
  resubmit() {
    this.setData({
      refuse: false
    })
    util.skip('/service/enter/enter?state=-1&token=' + this.data.token)
  },
  waitClose() {
    util.back()
  },
  chooseAvatar(e) {
    http.chooseImg(['album', 'camera'], true, true, this.data.token).then(res => {
      this.setData({
        avatarUrl: res.data.url
      })
    })
    // const {
    //   avatarUrl
    // } = e.detail

    // http.upload(avatarUrl, {
    //   type: 'image'
    // }, false, true, this.data.token).then(res => {
    //   this.setData({
    //     avatarUrl: res.data.url
    //   })
    // })
  },
  saveInfo() {
    http.post('index/updateuserinfo', {
      type: 'update',
      avatar: this.data.avatarUrl,
      nickname: this.data.nickname,
    }, true, false, this.data.token).then(res => {
      this.setData({
        show: false
      })

      util.toast(res.msg)
      if (this.data.userInfo.is_shop === 0) {
        this.getResult()
      } else if (this.data.userInfo.is_shop === 1) {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }
    })
  },
  nameInput(e) {
    this.setData({
      nickname: e.detail.value
    })
  },
  namereview(e) {},
  closeRefuse() {
    this.setData({
      refuse: false
    })
  },
  onClose() {
    this.setData({
      show: false
    })
    if (this.data.userInfo.is_shop === 0) {
      this.getResult()
    } else if (this.data.userInfo.is_shop === 1) {
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  },

  getCode() {
    let that = this
    wx.login({
      success(res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
        } else {
          this.getCode()
        }
      }
    })
  },

  read() {
    if (!this.data.agree) {
      wx.showToast({
        title: '请先阅读并同意《用户协议》《隐私政策》',
        icon: 'none'
      })
    }
  },
  getResult() {
    http.post('shop/apply', {}, true, false, this.data.token).then(res => {
      console.log(res)
      if (res.data) {
        if (res.data.state) {
          if (res.data.state == -1) {
            this.setData({
              refuse: true,
              note: res.data.note
            })
          } else if (res.data.state == 0) {
            this.setData({
              waitSHow: true
            })
          } else if (res.data.state == 1) {
            wx.reLaunch({
              url: '/service/enter/enter?token=' + this.data.token
            })
          }
        }
      } else {
        util.skip('/service/enter/enter?token=' + this.data.token)
      }
    })
  },
  getPhoneNumber(e) {

    http.post('user/userlogin', {
      code: this.data.code,
      type: 2,
      encryptedData: e.detail.encryptedData,
      iv: encodeURIComponent(e.detail.iv),
    }, true, false).then(res => {
      this.getCode()
      this.setData({
        userInfo: res.data.userInfo
      })
      if (res.data.userInfo.is_shop === 1) {
        wx.setStorageSync('token', res.data.user.token)

        app.globalData.token = res.data.user.token
        app.globalData.user = res.data.user
        app.globalData.userInfo = res.data.userInfo

      } else {
        this.setData({
          token: res.data.user.token
        })

      }

      if (res.data.userInfo.is_update === 0) {
        this.setData({
          show: true,
          avatarUrl: res.data.user.avatar,
          nickname: res.data.user.nickname
        })
      } else if (res.data.userInfo.is_shop === 0) {
        this.getResult()
      } else {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }
    }).catch(err => {
      this.getCode()
    })
  },

  clickread() {
    this.setData({
      agree: !this.data.agree
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.getCodeCountdownInter)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.getCodeCountdownInter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  inputChange(e) {
    console.log(e)
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [field]: value
    })
  },
  loginClick(){
    const {
      mobile, captcha
    } = this.data;
    if (!mobile) {
      wx.showModal({
        title: '提示',
        content: '请输入手机号！',
        showCancel: false
      })
      return
    }
    if (!captcha) {
      wx.showModal({
        title: '提示',
        content: '请输入验证码！',
        showCancel: false
      })
      return
    }
    http.post('/api/user/mobilelogin', {
      mobile: mobile,
      captcha: captcha,
    }, true, false).then(res => {
      console.log(res)
      wx.showToast({
        title: res.data.msg || "登录成功~",
        icon: "none"
      })
      this.setData({
        userInfo: res.data.userInfo
      })
      if (res.data.userInfo.is_shop === 1) {
        wx.setStorageSync('token', res.data.user.token)

        app.globalData.token = res.data.user.token
        app.globalData.user = res.data.user
        app.globalData.userInfo = res.data.userInfo

      } else {
        this.setData({
          token: res.data.user.token
        })

      }

      if (res.data.userInfo.is_update === 0) {
        this.setData({
          show: true,
          avatarUrl: res.data.user.avatar,
          nickname: res.data.user.nickname
        })
      } else if (res.data.userInfo.is_shop === 0) {
        this.getResult()
      } else {
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }
    }).catch(err => {
      console.log(err)
      wx.showModal({
        title: '提示',
        content: err.data.msg,
        showCancel: false
        
      })
      // this.getCodeCountdown()
    })
  },
  getMobileCode() {
    const {
      mobile
    } = this.data;
    if (!mobile) {
      wx.showModal({
        title: '提示',
        content: '请输入手机号！',
        showCancel: false
      })
      return
    }
    http.post('/api/sms/send', {
      mobile: mobile,
      event: 'mobilelogin',
    }, true, false).then(res => {
      console.log(res)
      wx.showToast({
        title: '验证码发送成功，请注意接受~',
        icon: "none"
      })
      this.getCodeCountdown()
    }).catch(err => {
      console.log(err)
      wx.showModal({
        title: '提示',
        content: err.data.msg,
        showCancel: false
        
      })
      // this.getCodeCountdown()
    })
  },
  getCodeCountdown(){

    const that = this;
    that.setData({
      countdown: 59
    })
    const codeCountdownInter = setInterval(() => {
      let {getCodeCountdownInter, countdown} = this.data;
      console.log(countdown)
      if(countdown<= 0){
        clearInterval(getCodeCountdownInter)
        that.setData({
          countdown: 0
        })
      } else {
        countdown--
        that.setData({
          countdown
        })
      }
    }, 1000)
    this.setData({
      getCodeCountdownInter: codeCountdownInter
    })
  }
})